<?php

namespace app\common\lib;

use Predis\Client as RedisClient;
use think\facade\Config;

class Redis
{
    private static $instance = [];

    public static function connect($config = [], $name = false)
    {

        if (false === $name) {
            $name = md5(serialize($config));
        }
        if (true === $name || !isset(self::$instance[$name])) {
            $dsn = self::parseConfig($config);
            if (true === $name) {
                $name = md5(serialize($config));
            }
            $parameters = [
                'database' => $dsn['db'],
            ];
            if (isset($dsn['password']) && (string)($dsn['password']) !== '') {
                $parameters['password'] = $dsn['password'];
            }
            $redisClient = new RedisClient([
                'scheme' => 'tcp',
                'host' => $dsn['host'],
                'port' => $dsn['port'],
            ], ['parameters' => $parameters, 'prefix' => $dsn['prefix']]);
            self::$instance[$name] = $redisClient;
        }
        return self::$instance[$name];
    }

    /**
     * 数据库连接参数解析
     * @access private
     * @param mixed $config 连接参数
     * @return array
     */
    private static function parseConfig($config): array
    {
        if (empty($config)) {
            $config = Config::get('redis');
        }
        return self::parseDsn($config);
    }

    private static function parseDsn($config): array
    {
        return [
            'host' => !isset($config['host']) ? '127.0.0.1' : $config['host'],
            'port' => !isset($config['port']) ? 6379 : $config['port'],
            'password' => !isset($config['password']) ? '' : $config['password'],
            'db' => !isset($config['database']) ? 0 : $config['database'],
            'prefix' => !isset($config['prefix']) ? '' : $config['prefix'],
        ];
    }


    public static function __callStatic($method, $params)
    {
        return call_user_func_array([self::connect(), $method], $params);
    }

    public static function db(int $db)
    {
        $cfg = Config::get('redis');
        $config = array_merge($cfg, ['database' => $db]);
        return self::connect($config);
    }
}